package dfbz.com.controller.Login;

import com.alibaba.druid.util.StringUtils;
import dfbz.com.constant.Const;
import dfbz.com.controller.BaseServlet;
import dfbz.com.model.User;
import dfbz.com.service.UserService;
import dfbz.com.service.impl.UserServiceImpl;
import dfbz.com.utils.MailUtil;
import dfbz.com.utils.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public LoginServlet() {
        super();
    }

    public void toLogin(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String rem = req.getParameter("rem");

            if (username != null & password != null) {
                User user = userService.findUserByName(username);
                if (password.equals(user.getPassword())) {
                    //登录之后在这里设置rem(记住我)不为空
                    if (null != rem) {

                        Cookie cookie = new Cookie("userInfo", username);
                        cookie.setMaxAge(Const.MAX_COOKIE_TIME);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                    //
                    req.getSession().setAttribute("userId", user.getId());

                    resp.sendRedirect(req.getContextPath() + "/view/home");
                    return;
                }
            }
            resp.sendRedirect(req.getContextPath() + "/");
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void toLogout(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Cookie[] cookies = req.getCookies();
            if (null !=cookies && cookies.length>0){
                for (Cookie cookie :cookies) {
                    if ("userInfo".equals(cookie.getName())){
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                        break;
                    }
                }
            }
            resp.sendRedirect(req.getContextPath() + "/");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void toRegister(HttpServletRequest req,HttpServletResponse resp){

        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String password2 = req.getParameter("password2");
            String email = req.getParameter("email");
            /*
             * 检查邮箱是否合法
             * 检查是否存在该用户
             * 检查密码是否一致
             * 检查用户是否已存在
             * 检查邮箱是否已存在
             */
            if (StrUtil.checkEmail(email)){
                if (null!= username && null!=password){
                    if (password.equals(password2)){
                        User user = userService.findUserByName(username);
                        if (null != user){
                            req.getSession().setAttribute("regErrorMsg","用户已存在");
                            req.getRequestDispatcher("/view/showRegister").forward(req,resp);
                        }else{
                            User userByEmail = userService.findUserByEmail(email);
                            if (userByEmail != null){
                                req.getSession().setAttribute("regErrorMsg","邮箱已存在");
                                req.getRequestDispatcher("/view/showRegister").forward(req,resp);
                            }else {
                                userService.addUser(email,username,password);
                                resp.sendRedirect(req.getContextPath()+"/view/index");
                            }
                        }
                    }else {
                        req.getSession().setAttribute("regErrorMsg","密码不一致");
                        req.getRequestDispatcher("/view/showRegister").forward(req,resp);
                    }
                }else {
                    req.getSession().setAttribute("regErrorMsg","用户名或密码不能为空");
                    req.getRequestDispatcher("/view/showRegister").forward(req,resp);
                }
            }else {
                req.getSession().setAttribute("regErrorMsg","请输入正确的邮箱");
                req.getRequestDispatcher("/view/showRegister").forward(req,resp);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void resetPassword (HttpServletRequest request,HttpServletResponse response) {
        try {
            String email = request.getParameter("email");
            String captcha = request.getParameter("captcha");
            String password = request.getParameter("password");

            if (StrUtil.checkEmail(email)){
                Object obj = request.getSession().getAttribute("email");
                if (null != obj){
                    String emailCode = obj.toString();
                    if (emailCode.equals(captcha)){
                        User user = userService.findUserByEmail(email);
                        if (null !=user){
                            userService.resetPassword(user.getId(),password);
                            response.sendRedirect(request.getContextPath()+"view/index");
                            return;
                        }
                    }
                }
            }
            request.getSession().setAttribute("ErrorForgetMsg","重置失败");
            response.sendRedirect(request.getContextPath()+"/view/forget");
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    public void sendCaptcha (HttpServletRequest request,HttpServletResponse response) {

        try{
            response.setHeader("contentType","text/html");
            String email = request.getParameter("email");
            HttpSession session = request.getSession();
            if (StrUtil.checkEmail(email)){
                Object obj = session.getAttribute("email");
                if (null !=obj){
                    response.getWriter().write("验证码已发送到您的邮箱，请查收");
                }else {
                    String title = "《小标交友验证码》";
                    String captcha = StrUtil.creatRandomNum();
                    String content = "验证码为："+captcha;
                    session.setAttribute(email,captcha);
                    session.setMaxInactiveInterval(Const.MAX_CAPTCHA_TIME);
                    //发送邮箱
                    MailUtil.send(email,title,content,MailUtil.UNICODE);
                }
                response.getWriter().write("验证码发送成功，请查收");
            }else {
                response.getWriter().write("邮箱格式不对，请重新输入");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
